package com.piece.core.framework.enums;

import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.nio.charset.Charset;

@Getter
public enum ContentType {

    FORM_URLENCODED("application/x-www-form-urlencoded"),
    MULTIPART("multipart/form-data"),
    JSON("application/json"),
    XML("application/xml"),
    JAVASCRIPT("application/x-javascript"),
    CSS("text/css"),
    SOAP("application/soap+xml"),
    STREAM("application/octet-stream"),
    TEXT_PLAIN("text/plain"),
    TEXT_XML("text/xml"),
    TEXT_HTML("text/html"),
    JEPG("image/jpeg"),
    PNG("image/png"),
    MP3("audio/mp3"),
    MP4("video/mp4");

    private final String value;

    ContentType(String value) {
        this.value = value;
    }

    public String toString() {
        return build(this.value, Charset.defaultCharset());
    }

    public String toString(Charset charset) {
        return build(this.value, charset);
    }

    public static boolean isDefault(String contentType) {
        return null == contentType || isFormUrlEncode(contentType);
    }

    public static boolean isFormUrlEncode(String contentType) {
        return StringUtils.startsWithIgnoreCase(contentType, FORM_URLENCODED.toString());
    }

    public static ContentType get(String body) {
        ContentType contentType = null;
        if (StringUtils.isNotBlank(body)) {
            char firstChar = body.charAt(0);
            switch (firstChar) {
                case '<':
                    contentType = XML;
                    break;
                case '[':
                case '{':
                    contentType = JSON;
            }
        }

        return contentType;
    }

    public static String build(String contentType, Charset charset) {
        return contentType + ";charset=" + charset.name();
    }
}